#pragma once
#include <iostream>
#include <memory>
#include <poll.h>
#include "Socket.hpp"
#include "Log.hpp"

using namespace socket_ns;

const static int N = 1024;;
const static int defaultfd = -1;
const static short defaultevents = 0;

class PollServer
{
public:
    PollServer(uint16_t port)
        : _port(port),
          _listensocke(std::make_unique<TcpSocket>()),
          _timeout(-1)
    {
        InterAddr addr("0", _port);
        _listensocke->BuidListenSocket(addr);
        for (int i = 0; i < N; i++)
        {
            _events[i].fd = defaultfd;
            _events[i].events = defaultevents;
            _events[i].revents = defaultevents;
        }
        // 将listensocke添加到poll中
        _events[0].fd = _listensocke->SockFd();
        _events[0].events = POLLIN;
        _events[0].revents = defaultevents;
    }

    void AcceptClient()
    {
        InterAddr clientaddr;
        // 接收新连接，这里调用Accepter
        int sockfd = _listensocke->Accpeter(&clientaddr);
        if (sockfd < 0)
        {
            LOG(ERROR, "Accept error...\n");
            return;
        }
        LOG(INFO, "Get a New client, sockfd: %d, client info %s:%d\n", sockfd, clientaddr.Ip().c_str(), clientaddr.Port());
        // 将新的连接添加到select中，而这里只需要将新的文件描述添加到辅助数组即可
        int pos = 1;
        for (; pos < N; pos++)
        {
            if (_events[pos].fd == defaultfd)
                break;
        }
        if (pos == N)
        {
            // 数组已经满了，无法添加新的文件描述符，直接关闭这个文件描述符
            ::close(sockfd);
            LOG(WARNING, "evenst is full, close new sockfd: %d\n", sockfd);
            return;
        }
        else
        {
            // 添加新的文件描述符
            _events[pos].fd = sockfd;
            _events[pos].events = POLLIN;
            _events[pos].revents = defaultevents;
            LOG(DEBUG, "Add new sockfd to Array, sockfd: %d\n", sockfd);
        }
    }

    void ServiceIO(int pos)
    {
        char buffer[1024];
        int sockfd = _events[pos].fd;
        ssize_t n = ::recv(sockfd, buffer, sizeof(buffer) - 1, 0); // 所以这里在读取的时候就不会被阻塞了，因为数据以及就绪了
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "[client say]# " << buffer << std::endl;
            std::string echo_str = "[server echo]# ";
            echo_str += buffer;
            ::send(sockfd, echo_str.c_str(), echo_str.size(), 0);
        }
        else if (n == 0)
        {
            // 说明客户端已经关闭了，或者网络异常了
            LOG(INFO, "%d Client close or network error...\n", sockfd);
            ::close(sockfd);    // 关闭文件描述符
            _events[pos].fd = defaultfd; // 将这个文件描述符置为默认值
            _events[pos].events = defaultevents;
            _events[pos].revents = defaultevents;
            LOG(DEBUG, "curr fd_array[] fd list : %s \n", PrintFd().c_str());
        }
        else
        {
            // 说明客户端已经关闭了，或者网络异常了
            LOG(INFO, "%d Client recv error...\n", sockfd);
            ::close(sockfd);    // 关闭文件描述符
            _events[pos].fd = defaultfd; // 将这个文件描述符置为默认值
            _events[pos].events = defaultevents;
            _events[pos].revents = defaultevents;
            LOG(DEBUG, "curr fd_array[] fd list : %s \n", PrintFd().c_str());
        }
        LOG(DEBUG, "curr fd_array[] fd list : %s \n", PrintFd().c_str());
    }

    void HanderEvent()
    {
        // 可能有多个文件描述符就绪了
        for (int i = 0; i < N; i++)
        {
            if (_events[i].fd == defaultfd)
                continue;
            if (_events[i].revents & POLLIN)
            {
                // 说明有文件描述符就绪了
                // 说明有新连接，需要处理新连接，将新连接也就是新的文件描述符添加的辅助数组中
                if (_events[i].fd == _listensocke->SockFd())
                {
                    AcceptClient();
                }
                else
                {
                    // 说明有数据需要处理，也就是普通的已经存在的socekt
                    // 到这里之后等的工作已经结束，这里就可以直接进行IO处理了
                    ServiceIO(i);
                }
            }
        }
    }
    void Loop()
    {
        while (true)
        {
            int n = ::poll(_events, N, _timeout);
            switch (n)
            {
            case 0:
                LOG(INFO, "timeout....\n");
                break;
            case -1:
                LOG(ERROR, "poll error...\n");
                break;
            default:
                // 说明有事件发生
                LOG(INFO, "Event happent, n : %d\n", n); // 底层有一个事件就绪了，select就会一直进行通知，直到把这个事件处理完
                HanderEvent();
                break;
            }
        }
    }
    std::string PrintFd()
    {
        std::string fdstr;
        for (int i = 0; i < N; i++)
        {
            if (_events[i].fd == defaultfd)
                continue;
            fdstr += std::to_string(_events[i].fd) + " ";
        }
        return fdstr;
    }
    ~PollServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensocke;
    int _timeout;
    struct pollfd _events[N];
};